 var xmlDoc,xmlhttp;
  
 
 
 
 var mainPanel,mapPanel,startPanel,formPanel, bar;
 var markBubble,markerYourPos ;  

 var markBubble;
 var markers=[];
 
 
 
var title0="";
var title1="set positions";
var title2="set direction";


var nrB = 0 ;
var index = 0;
var stations=[];
 
 var c_latLng;
 var c_lat = 45.785000000;
 var c_long = 24.150000000; 
 
 
 ////////////////////////////////////////STRUCTURES//////////////////////////////////////

 function station(id,lat,long,name,dir,busses){
 	 this.id= id;
 	 this.latitude= lat;
 	 this.longitude = long;
 	 this.name = name;		
 	 this.direction = dir;
 	 this.busses = busses;
 	  
  }  
 
 
 
 /////////////////////
 function phpUBS(  )
 { 
    xmlhttp=new XMLHttpRequest(); 
    xmlhttp.open("GET","php/updateStationBusList.php",false);
    xmlhttp.send();
     
  
 };
 /////////////////////////////////OBJECT IMPLEMENTATIONS/////////////////////////////////////
 function initObjects(){
	  
 btnL = new Ext.Button({
		iconMask: true,
		centered: true,
		visible: false,
		iconCls: 'arrow_left',
		ui: 'plain',
		style: 'margin:0;',
		handler: goLeft 
});
btnR = new Ext.Button({ 
	iconMask: true,
	centered: true,
	iconCls: 'arrow_right',
	ui: 'plain',
	style: 'margin:0;',
	handler: goRight
} );



 
mapPanel =  new Ext.Map({
 title: title1,  
   useCurrentLocation: false,
	mapOptions: {
		zoom: 14,
		center: c_latLng
		} 			 
}); 
//
//startPanel =  new Ext.Panel({
//	title: 'Map' ,
//	html: "<div id='firstPage'>Get the first 10 Stations</div>"
//}); 
formPanel = new   Ext.form.FormPanel ({
    fullscreen: true,
    title: 'Form',
    padding: 4,
    scroll: 'vertical' 
      
});


startPanel =  new Ext.form.FormPanel({
	title: 'Map' ,
	padding: 4,
    scroll: 'vertical' ,
	//html: "<div id='firstPage'>Get the first 10 Stations</div>",
		items: [{ 
	        xtype: 'selectfield',
	        name : 'bus',
	        label: 'Pick bus:',
	        options: [
	                {text: '1',  value: '1'},
	                {text: '2', value: '2'},
	                {text: '5', value: '3'},
	                {text: '10', value: '4'},
	                {text: '11', value: '5'},
	                {text: '12', value: '6'},
	                {text: '13', value: '7'},
	                {text: '14', value: '8'},
	                {text: '15', value: '9'},
	                {text: '16', value: '10'},
	                {text: '17', value: '11'},
	                {text: '18', value: '12'},
	                {text: '111', value: '13'},
	                {text: '112', value: '14'},
	                {text: '113', value: '15'},
	                {text: '114', value: '16'},
	                {text: '115', value: '17'},
	                {text: '116', value: '18'},
	                {text: '117', value: '19'},
	                {text: '118', value: '20'},
	                {text: '22', value: '21'},
	                {text: '23', value: '22'}
	                ]
		        }]
}); 

 }


/////////////////////////////////////FUNCTIONS//////////////////////////////////
function goToOne(){
	c_latLng =  c_latlng = new google.maps.LatLng(c_lat,c_long);
	mapPanel.update(c_latLng);//mapPosition is the new lat,long
		mapPanel.rendered = false;
		mapPanel.render();
		addMarker();
		bar.setTitle(title1); 
		btnL.setVisible(true);

		mainPanel.setActiveItem(1);	
		var id_bus = getIdBus();
		phpGetStations( id_bus);
}
function getIdBus(){
	var ret = startPanel.getValues();  
	return ret["bus"];
}
function goToTwo(){
	bar.setTitle(title2);
}
function goRight(){
	 
	 	
		
		if(index==0){ 
           goToOne();
 		     
			 
			}
		
		if(index==1){
 			bar.setTitle(title2);
 
 			addAllFields(); 
 		mainPanel.setActiveItem(2);			 
		}
		 
		if(index == 2){
 			
 
 			bar.setTitle(title0);
 			btnL.setVisible(false);
 			mainPanel.setActiveItem(0);		
 			

 			formPanel.items.clear();
 			formPanel.doLayout();
 			clearStations(); 
 			index = -1;

 			 phpUBS();
		}
		index = index + 1;

};
  
function goLeft(){
	 
	
	if(index==1){
 		bar.setTitle(title0);
 		btnL.setVisible(false); 
 		mainPanel.setActiveItem(0);		
//		btnR.setVisible(true); 
//		clearBusStations(); 
	}
	if(index==2){
 	bar.setTitle(title1);
 	mainPanel.setActiveItem(1);		
//		btnR.setVisible(true); 
//		getStations(markerYourPos.position.Ra,markerYourPos.position.lat());
//		
//		mainPanel.setActiveItem(0);  
	}
	if(index==3){
		mainPanel.setActiveItem(1);		
//		bussesPanel.removeAll();
//		bar.setTitle(title3);
//		btnR.setVisible(false);  
//		hoursInterval = clearInterval ( hoursInterval );
//		clearSelectedBusses();
//		getBusses(station_id);
//		 
//		addBussesToPanel(); 
	}
	index = index - 1;
};

function addMarker(){
	var coords = mapPanel.mapOptions.center;
	//set marker on mapbearing2009
	
		 c_latLng =    new google.maps.LatLng(c_lat,c_long);
		markerYourPos = new google.maps.Marker({
		 map: mapPanel.map,
		 position: c_latLng,
		 draggable: true, 
		 icon:'images/icons/hereIcon.png',
		 shadow: 'images/icons/shIcon.png'
	    });
	  
	  
	 google.maps.event.addListener(markerYourPos, "click",function(){
	 	 markBubble.setContent("your position ");
	     markBubble.open(mapPanel.map,markerYourPos);
	   });
};


function phpGetStations(id_bus )
{
	clearStations();
   xmlhttp=new XMLHttpRequest(); 
   xmlhttp.open("GET","php/getStations.php?id_bus="+id_bus,false);
   xmlhttp.send();
   convertStations();
   addStationsToMap();  
 
};

function convertStations(long ,lat){
	if(xmlhttp.readyState == 0){
		xmlhttp.send();
	}
	while(xmlhttp.readyState ==3){

 }
 if(xmlhttp.readyState == 4 && xmlhttp.responseXML != null )
    {
		   xmlDoc=xmlhttp.responseXML; 
	   var root = xmlDoc.getElementsByTagName("xml");
	    
	   for(var i=0; i<root[0].childNodes.length;i++){
		    //Create a new row for tbody
		 //  Ext.Msg.Alert('xml',root[0]);
		   var item= root[0].childNodes[i]  ;
		   var st = new station(
				   item.childNodes[0].childNodes[0].data,
				   0,
				   0,
//				   item.childNodes[1].childNodes[0].data,
//				   item.childNodes[2].childNodes[0].data,
				   item.childNodes[1].childNodes[0].data,
//				   item.childNodes[4].childNodes[0].data,
				   0,
				   0
//				   item.childNodes[5].childNodes[0].data
		   ); 
		 stations.push(st);
	   } 
    }
}

function addStationsToMap(){
	  for(var i=0; i<stations.length ;i++){
		  addStation(stations[i]);
	  }
}
function addStation(station){ 
	//set marker on mapbearing2009
	 c_latLng =    new google.maps.LatLng(c_lat,c_long);
    var marker = new google.maps.Marker({
		 map: mapPanel.map,
		 position: c_latLng,
		 draggable: true, //tre sa fie draggable ca sa functioneze bubble>>>>???/ 
		 title:station.id,
		 icon:'images/icons/busStopIcon.png',
		 shadow: 'images/icons/shIcon.png'
	    });
    markers.push(marker);
	  
	  
	 google.maps.event.addListener(marker, "click",function(){
		  var content= "<div>"+station.name+"</br>"+station.direction+"</div>";
		  station_id= marker.getTitle();
		  markBubble.setContent(   content);
	      markBubble.open(mapPanel.map,marker);
	      btnR.setVisible(true); 
	  });
};

function clearStations(){
	 for (var i= markers.length; i >0 ; i--) {
		 markers.pop().setMap(null); // remove markers from map 
		};
		 markers = []; 
		 stations= [];
	 
};







/////   form part
function addAllFields(){
	formPanel.items.clear();
	formPanel.doLayout();
	 for(var i=0; i<markers.length ;i++){
		 if(markers[i].position.lat() != markerYourPos.position.lat() || 
				 	markers[i].position.lng() != markerYourPos.position.lng() ) 
			 			addField(markers[i].position,stations[i]);
	  }
	 
	 formPanel.add({
     	xtype: 'button',
     	name: 'btnSubmit',
     	text: 'Update', 
     	align: 'center',
     	ui: 'round',
     	margin: 5,
     	handler: submit
     } );
     formPanel.add({ 
     	hidden: true,
     	html: 'Data saved to DB !'
     	});
}
function addField(pos,station){  

	
	nrB= nrB +1;
	formPanel.add({xtype: 'spacer'});
	formPanel.add({
        xtype: 'textfield',
        name : 'id'+nrB,
        label: 'id',
        value: station.id,
        hidden: true
    } );
	formPanel.add({
        xtype: 'textfield',
        name : 'name'+nrB,
        label: 'Name',
        disabled: true,
        value:station.name 
    } );

	formPanel.add({
        xtype: 'textfield',
        name : 'lat'+nrB,
        label: 'Latitude',
        disabled: true,
        value: pos.lat()
    } );
	
	formPanel.add({
        xtype: 'textfield',
        name : 'long'+nrB,
        label: 'Longitude',
        disabled: true,
        value: pos.lng()
    } );
	
	formPanel.add({
        xtype: 'selectfield',
        name : 'dir'+nrB,
        label: 'Direction ',
        options: [
                {text: 'centru',  value: 'towards City Center'},
                {text: 'periferie', value: 'away from City Center'} 
                ]
          
    } );
	
	
	formPanel.setScrollable('vertical');
	formPanel.doLayout();
	
};

function submit(){
	updateStations()
  	formPanel.items.items[formPanel.items.items.length-2].setVisible(false);
 	formPanel.items.items[formPanel.items.items.length-1].setVisible(true);
}
function updateStations(){
	var temp = formPanel.getValues(); 
	 for(var j=1;j<=nrB;j++){
		
		  
		  phpUpdateStation(temp["id"+j],temp["lat"+j],temp["long"+j],temp["dir"+j] );
		 
	 }
}
function phpUpdateStation(id ,lat,long,dir){
	  xmlhttp=new XMLHttpRequest(); 
	   xmlhttp.open("GET","php/updateStation.php?id="+id+"&lat="+lat+"&long="+long+ "&dir="+dir,false);
	   xmlhttp.send();
	   
	   
}
//////////////////////////////MAIN////////////////////////////


Ext.setup({
	
 //bara  de sus
 statusBarStyle:  'black-translucent', 
 glossOnIcon: false, 
  
 onReady: function(){
		//object
   markBubble = new google.maps.InfoWindow(); 
   c_latLng =    new google.maps.LatLng(c_lat,c_long);
   initObjects();
   btnL.setVisible(false);
	
	 
	bussesPanel =  new Ext.Panel({
		 
    }); 
	
	bar = new Ext.Toolbar({
			dock: 'top', 
			items:[btnL,{xtype:'spacer'},btnR]
	});
		  
	mainPanel = new Ext.Panel({
			 fullscreen: true, 
			 layout:'card',
	             	
			    cardSwitchAnimation: 'cube', 
			    items: [startPanel, mapPanel, formPanel],
			    dockedItems:[ bar ]
	}); 
	
	
 function refreshMap(){
	addMarker();
 }
	   
	//smapPanel.geo.on('update', refreshMap);
	}
});